package com.elem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.elem.bean.User;
import com.elem.service.UserService;
import com.elem.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

// 目前只有两个：一个是登录，一个是注册
@WebServlet("/UserController/*")//和  vsCode对应
public class UserServlet extends BaseServlet {
//      在web层调用Service层的方法，完成业务处理，在这里创建对象
    UserService userService =  new UserServiceImpl();
//
    ObjectMapper objectMapper = new ObjectMapper();
    // 检验用户手机号是否存在
    public void getUserById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       拿到获取的id，即通过前端页面输入的  手机号=userId
        String userId = req.getParameter("userId");

        try {
            User user = userService.getUserById(userId);

            // 如果user不为空，说明该手机号已被注册
            if (user != null) {
                // 前端接收的数据是整数数据，判断 是否 == 1 说明该手机号已被注册
                objectMapper.writeValue(resp.getOutputStream(), 1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void saveUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user  = new User();
        try {
            BeanUtils.populate(user,req.getParameterMap());
            int row = userService.saveUser(user);
            objectMapper.writeValue(resp.getOutputStream(), row);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void getUserByIdByPass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user  = new User();
        try {
            BeanUtils.populate(user,req.getParameterMap());
            User resUser = userService.getUserByIdByPass(user.getUserId(), user.getPassword());
            objectMapper.writeValue(resp.getOutputStream(), resUser);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}